package com.education.util;


import org.apache.poi.ss.formula.functions.T;

import java.io.*;

/**
 * Created by lzh on 2017/8/16.
 * 封装序列化和反序列化方法
 */
public class SerialUtil {

    /**
     * 将对象序列化成字节数组
     * @param object
     * @return
     */
    public static byte[] Object2Bytes(Object object){
        if (object!=null){
            ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
            ObjectOutputStream oos= null;
            byte [] bytes=null;
            try {
                oos = new ObjectOutputStream(byteArrayOutputStream);
                oos.writeObject(object);
                bytes=byteArrayOutputStream.toByteArray();
            }
            catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    oos.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return bytes;
        }
       return null;
    }

    /**
     * 将字节数组序列化成对象
     * @param bytes
     * @param <T>
     * @return 对应的对象
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static <T extends Serializable> T bytes2Object(byte[] bytes)  {
        if (bytes!=null){
            ByteArrayInputStream bai=new ByteArrayInputStream(bytes);
            ObjectInputStream ois = null;
            Object object=null;
            try {
                ois = new ObjectInputStream(bai);
                object=ois.readObject();
            }
            catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    ois.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return (T)object;
        }
        return null;
    }
}
